﻿using System;
using System.Net;
using System.Net.Sockets;
using RFDeviceNet;

namespace DemoSharp
{
    class PacketWorker : IDisposable
    {
        private static Socket _soc;
        private static IPEndPoint _localIpe;
        private static ConnectionInfo _connection;

        public PacketWorker()
        {
            _connection = new ConnectionInfo();
            _soc = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp) {ReceiveTimeout = 3000};
            _localIpe = new IPEndPoint(IPAddress.Any, 6001);
            _soc.Bind(_localIpe);
            
        }

        public _UDP_DEVINFOBLOCK_PC_Net GetUdpPcketFrom620()
        {
            var count = _soc.Receive(_connection.Buffer);
            var mas = new byte[count];
            Buffer.BlockCopy(_connection.Buffer, 0, mas, 0, count);
            var block = GetBlock(mas);
            return block;
        }

        private static _UDP_DEVINFOBLOCK_PC_Net GetBlock(byte[] mas)
        {
            if (mas.Length != 268)
            {
                throw new Exception("wrong packet length");
            }
            var block = new _UDP_DEVINFOBLOCK_PC_Net();
            var devTypeBuf = new byte[2];
            Buffer.BlockCopy(mas, 0, devTypeBuf, 0, 2);
            block.DeviceType = BitConverter.ToUInt16(devTypeBuf, 0);
            Buffer.BlockCopy(mas, 2, block.IP, 0, 4);
            Buffer.BlockCopy(mas, 6, block.MAC, 0, 4);
            Buffer.BlockCopy(mas, 10, block.Info, 0, 256);
            return block;
        }

        class ConnectionInfo
        {
            public ConnectionInfo()
            {
                Buffer = new byte[1000];
            }

            public Byte[] Buffer { get; private set; }
        }

        public void Dispose()
        {
            _soc.Disconnect(true);
            _soc.Shutdown(SocketShutdown.Both);
            _soc.Close();
        }
    }
}
